﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Data;
using System.Net;
using System.Data.SqlClient;
using System.Configuration;
using System.Runtime.InteropServices;
using System.IO;

namespace Socket服务器
{
    /// <summary>
    /// ServerManager.xaml 的交互逻辑
    /// </summary>
    public partial class ServerManager : Window
    {

        public ServerManager()
        {
            InitializeComponent();
            listbox.ItemsSource = serversource.SCollection;
            ServerInit();
            Console.Title = "监视平台切勿关闭";
            Instance = this;
        }

        public static  ServerManager Instance { get; set; }

        bool  IsSql = true;
        private bool cansql()
        {
            return IsSql;
        }
        private void ServerInit()
        {
            if (IsSql==false )
                return;
            DataTable dt=SocketConfig.ReadConfig (); 
            foreach (DataRow DR in dt.Rows)
            {
                ServerConfig SC = new ServerConfig();               
                SC.ServerName = (string)DR["ServerName"];
                SC.ServerPort = Convert.ToInt16 ( DR["ServerPort"]);
                SC.CapaCity  = Convert.ToInt16(DR["ServerCapacity"]);
                SC.ServerIP = System.Net.IPAddress.Parse((string )DR["ServerIp"]);
                serversource.ServerAdd(SC);
                AddServer(serversource.NewAddSocketManager);
                serversource.NewAddSocketManager.ServerContent = ServerStarOrStop(SC.ServerPort);
                serversource.NewAddSocketManager = null;
               
            }
        }
        
        ServerSource serversource = new ServerSource();

        public  void AddServer(SocketManager S)
        {
            SocketManager.DeleteThis SD = new SocketManager.DeleteThis(deleteserver);
            SocketManager.Cansql SC=new SocketManager.Cansql(cansql);
            S.DeleteServer = SD;
            S.CanSql = SC;
            OpenSocketManager(S.Port);
            listbox.SelectedIndex = listbox.Items.Count - 1;

        }

        private void listbox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                if (listbox.SelectedItem == null)
                    return;
                frame.Opacity = 100;     
                int port = ((SocketManager)listbox.SelectedItem).Port;
                OpenSocketManager(port);
            }
            catch (Exception ex)
            {
                LogException.WriteLogToFile(ex);
            
            }
        }


        private void OpenSocketManager(int port)
        {
            try
            {  
                frame.Navigate(serversource.GetServer(port));
                frame.NavigationService.RemoveBackEntry();
            }
            catch (Exception ex)
            {
                LogException.WriteLogToFile(ex);
            }
        }

        private void ADDServer_Click(object sender, RoutedEventArgs e)
        {
            AddServers AS = new AddServers(serversource);
            AS.ShowDialog();
            if (serversource.NewAddSocketManager != null)
            {
                AddServer(serversource.NewAddSocketManager);
                    SocketConfig.AddServers (serversource.NewAddSocketManager.SName ,
                        serversource.NewAddSocketManager.Port.ToString(),
                        serversource.NewAddSocketManager.CapaCity.ToString(), 
                        serversource.NewAddSocketManager.IP.ToString());
                serversource.NewAddSocketManager = null;
            }
        }

        private void deleteserver(SocketManager socketmanager)
        {
           if (serversource.DeleteServer(socketmanager.Port ))
            {            
                    SocketConfig.DelServers (socketmanager.Port.ToString(),socketmanager.IP.ToString());
                int pos = listbox.SelectedIndex;
                frame.Opacity = 0;
                if (listbox.Items.Count > 0)
                    listbox.SelectedIndex = 0;
            }
               
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {          
            Button B = (Button)sender;
            int port = Convert.ToInt16(B.Tag);
            B.Content=ServerStarOrStop(port);
        }

        public  string  ServerStarOrStop(int port)
        {
            try
            {
                SocketManager SM = serversource.SCollection.Where(x => x.Port == port).FirstOrDefault();
                listbox.SelectedItem = SM;
                return SM.ServerOper(SM.NewSC);

            }
            catch (Exception ex)
            {
                LogException.WriteLogToFile(ex);
                return "";
            }     
           
        }

        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            int count = serversource.SCollection.Where(c => c.ISRun == true).Count();
            if (count > 0)
            {
                e.Cancel = true;
                MessageBox.Show("必须先停止所有服务才能退出！");
            }
            SockLib.Device.ModbusDevices.ModBusDevice.SaveConfig();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
        }



        private void TextBlock_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            throw new Exception("UI：手动复位服务器");
        }

        private void TextBlock_MouseLeftButtonUp_1(object sender, MouseButtonEventArgs e)
        {
            UpdateLog UP = new Socket服务器.UpdateLog();
            UP.ShowDialog();
        }
    }
}
